<template>
  <div class="content"><div id="map"></div></div>
</template>
<script>
export default {
  data() {
    return {
      ros: null,
      viewer: null,
      gridClient: null,
      tfClient: null,
      path: null,
    };
  },
  methods: { 
    init() {
      // Connect to ROS.
      this.ros = new ROSLIB.Ros({
        url: "ws://192.168.112.128:9090",
      });

      const ratio = 125 / 115;
      let newWidth = window.innerWidth - 450;
      let newHeight = window.innerHeight - 150;
      if ((window.innerWidth - 450) / (window.innerHeight - 150) > ratio) {
        newWidth = (window.innerHeight - 150) * ratio;
        newHeight = window.innerHeight - 150;
      } else {
        newWidth = window.innerWidth - 450;
        newHeight = (window.innerWidth - 450) / ratio;
      }
      //1、 Create the main viewer.
      this.viewer = new ROS3D.Viewer({
        divID: "map",
        width: newWidth,
        height: newHeight,
        antialias: true,
      });

      console.log("Viewer created successfully", this.viewer);
      // 监听连接
      this.ros.on("connection", () => {
        console.log("成功连接到ROS");
      });
      // 监听错误
      this.ros.on("error", (error) => {
        console.log("ROS连接错误: ", error);
      });
      // 监听关闭
      this.ros.on("close", () => {
        console.log("ROS连接关闭");
      });
 
      // 2、创建地图客户端
      this.gridClient = new ROS3D.OccupancyGridClient({
        ros: this.ros,
        rootObject: this.viewer.scene,
        continuous: true,
      });

      //3、 创建用于显示路径的线
      this.tfClient = new ROSLIB.TFClient({
        ros: this.ros,
        fixedFrame: "map", // 你的固定坐标系
        angularTolerance: 0.05, // 允许的角度误差：5度（0.05弧度）
        translinearTolerance: 0.05, // 允许的平移误差：5厘米（0.05米）
      });
      this.path = new ROS3D.Path({
        ros: this.ros,
        tfClient: this.tfClient,
        rootObject: this.viewer.scene,
        color: createjs.Graphics.getRGB(173, 216, 230), //默认路径为亮蓝色
      });
    },
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.ros.close();
  },
};
</script>
<style lang="less" scoped>
.content {
  // height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  #map{
    border:1px solid #494141
  }
}
</style>
